from PyQt5.QtWidgets import QTableWidgetItem, QAbstractItemView, QLabel, QFrame, QStackedWidget, QHBoxLayout, QGridLayout, QTableWidget
from PyQt5.QtGui import QFont
from qfluentwidgets import PrimaryPushButton, FluentIcon, SearchLineEdit, ProgressBar
from components.info import *
from components import NetworkImageView
from services.controller import get_info, download_file

class SingleDownloadView(QFrame):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName('SingleDownloadView')
        self.layout = QGridLayout(self)
        self.layout.setContentsMargins(10, 80, 10, 10)
        self.layout.setSpacing(10)

        self.lineEdit = SearchLineEdit(self)
        self.lineEdit.setFixedSize(800, 35)
        self.lineEdit.setClearButtonEnabled(True)
        self.lineEdit.setPlaceholderText("请输入短视频链接")
        self.layout.addWidget(self.lineEdit, 0, 0)

        self.downloadButton = PrimaryPushButton(FluentIcon.DOWNLOAD, 'Download', self)
        self.searchButton = PrimaryPushButton(FluentIcon.SEARCH, 'Search', self)
        self.layout.addWidget(self.searchButton, 0, 1)
        self.layout.addWidget(self.downloadButton, 0, 2)

        self.tableWidget = QTableWidget(self)
        self.tableWidget.setFrameShape(QFrame.NoFrame)
        self.tableWidget.setFrameShadow(QFrame.Plain)
        self.tableWidget.setSelectionMode(QAbstractItemView.NoSelection)
        self.tableWidget.setColumnCount(1)
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setRowCount(6)

        font = QFont()
        font.setFamily("Microsoft YaHei Light")
        font.setPointSize(15)
        item = QTableWidgetItem("视频来源：")
        item.setFont(font)
        self.tableWidget.setVerticalHeaderItem(0, item)
        item = QTableWidgetItem("昵称：")
        item.setFont(font)
        self.tableWidget.setVerticalHeaderItem(1, item)
        item = QTableWidgetItem("描述：")
        item.setFont(font)
        self.tableWidget.setVerticalHeaderItem(2, item)
        item = QTableWidgetItem("大小：")
        item.setFont(font)
        self.tableWidget.setVerticalHeaderItem(3, item)
        item = QTableWidgetItem("视频链接：")
        item.setFont(font)
        self.tableWidget.setVerticalHeaderItem(4, item)
        item = QTableWidgetItem()
        item.setText("视频封面：")
        item.setFont(font)
        self.tableWidget.setVerticalHeaderItem(5, item)

        self.tableWidget.horizontalHeader().setVisible(False)
        self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
        self.tableWidget.horizontalHeader().setDefaultSectionSize(200)
        self.tableWidget.horizontalHeader().setMinimumSectionSize(100)
        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.tableWidget.verticalHeader().setVisible(True)
        self.tableWidget.verticalHeader().setCascadingSectionResizes(False)
        self.tableWidget.verticalHeader().setDefaultSectionSize(30)
        self.tableWidget.verticalHeader().setMinimumSectionSize(35)
        self.tableWidget.verticalHeader().setSortIndicatorShown(False)
        self.tableWidget.verticalHeader().setStretchLastSection(True)
        self.layout.addWidget(self.tableWidget, 1, 0, 1, 3)

        self.bar = ProgressBar(self)
        self.layout.addWidget(self.bar, 2, 0, 1, 3)


class SingleDownloadInterface(QFrame):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName('SingleDownload')
        self.stackWidget = QStackedWidget(self)
        self.layout = QHBoxLayout(self)
        self.downloadLabel = QLabel(self.tr("单视频下载"), self)
        self.pic_label = None
        self.__initWidget()

    def __initWidget(self):
        self.homeFrame = SingleDownloadView(self)
        self.stackWidget.addWidget(self.homeFrame)
        self.stackWidget.setCurrentIndex(0)

        # initialize style sheet
        self.__setQss()

        # initialize layout
        self.__initLayout()
        self.__connectSignalToSlot()

    def __initLayout(self):
        self.downloadLabel.move(60, 63)
        self.layout.setContentsMargins(10, 80, 10, 10)
        self.layout.setSpacing(0)
        self.layout.addWidget(self.stackWidget)
        pass

    def __setQss(self):
        """ set style sheet """
        self.stackWidget.setObjectName('stackWidget')
        self.downloadLabel.setObjectName('downloadLabel')
        self.downloadLabel.resize(200, 63)
        self.setStyleSheet(
            "QLabel#downloadLabel {"
            "font: 33px 'Microsoft YaHei Light';"
            "background-color: transparent;"
            "color: black;"
            "}")

    def __connectSignalToSlot(self):
        self.homeFrame.searchButton.clicked.connect(self.searchInfo)
        self.homeFrame.downloadButton.clicked.connect(self.downloadVideo)
        self.homeFrame.lineEdit.textChanged.connect(self.update_button_state)

    def searchInfo(self):
        link = self.homeFrame.lineEdit.text()
        if not link:
            createErrorInfoBar("注意：", "link is none", self)
            return

        msg = get_info(link)

        if not msg.is_success():
            createErrorInfoBar("爬取失败，原因是：", msg.get_data(), self)
            return

        result = msg.get_data()
        video_type = result["video_type"]
        desc = result["desc"]
        nickname = result["nickname"]
        size = str(result["size"])
        video_link = result["video_link"]
        pic_url = result["cover"]
        info = (video_type, nickname, desc, size, video_link)
        for x in range(len(info)):
            item = QTableWidgetItem(info[x])
            self.homeFrame.tableWidget.setItem(x, 0, item)

        self.pic_label = NetworkImageView(pic_url)
        self.pic_label.imageLoadedSignal.connect(self.on_image_loaded)
        self.homeFrame.searchButton.setEnabled(False)

    def on_image_loaded(self, pixmap):
        print("收到pixmap")
        # 更新单元格或其他操作
        self.pic_label.setParent(None)  # 取消原有父对象关联，避免重复添加
        self.homeFrame.tableWidget.setCellWidget(5, 0, self.pic_label)
        self.pic_label.setPixmap(pixmap)

    def downloadVideo(self):
        createSuccessInfoBar("恭喜你！", "download success!", self)

    def update_button_state(self, text):
        """
        当line_edit的文本发生变化时，这个方法会被调用。
        根据文本内容决定是否禁用按钮。
        """
        if len(text) > 0:
            self.homeFrame.searchButton.setEnabled(True)


